<template>
  <div class="schedule-add-container">
    <h2 style="text-align:center; margin: 20px 0;">添加排班</h2>
    
    <div class="schedule-header">
      <el-form :inline="true">
        <el-form-item label="排班月份:">
          <el-select v-model="selectedMonth" placeholder="请选择月份" style="width: 150px;">
            <el-option
              v-for="item in monthOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="护士名称:">
          <el-select v-model="selectedNurse" placeholder="请选择护士" style="width: 150px;">
            <el-option
              v-for="nurse in nurseOptions"
              :key="nurse.nurseCode"
              :label="nurse.name"
              :value="nurse.nurseCode"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <div class="schedule-grid">
      <div v-for="(day, idx) in days" :key="day.date" class="schedule-card">
        <div class="card-header">
          <span class="day-number">{{ day.date }}号</span>
          <span class="weekday">{{ day.weekday }}</span>
        </div>
        <div class="shift-options">
          <el-radio-group v-model="shifts[idx]" class="shift-radio-group">
            <el-radio label="早班" class="shift-radio">
              <div class="shift-label">
                <div class="radio-dot"></div>
                早班
              </div>
            </el-radio>
            <el-radio label="中班" class="shift-radio">
              <div class="shift-label">
                <div class="radio-dot"></div>
                中班
              </div>
            </el-radio>
            <el-radio label="晚班" class="shift-radio">
              <div class="shift-label">
                <div class="radio-dot"></div>
                晚班
              </div>
            </el-radio>
            <el-radio label="休息" class="shift-radio">
              <div class="shift-label">
                <div class="radio-dot"></div>
                休息
              </div>
            </el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>

    <div class="action-buttons">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onSubmit">添加</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import http from '@/api/http'

const router = useRouter()

const monthOptions = [
  ...Array.from({length: 12}, (_, i) => {
    const month = (i + 1).toString().padStart(2, '0');
    return [`2025-${month} 上`, `2025-${month} 下`];
  }).flat()
]

const nurseOptions = ref<any[]>([])
const selectedMonth = ref(monthOptions[0])
const selectedNurse = ref('')

// 获取护士列表
const getNurseList = async () => {
  try {
    const response = await http.get('api/WorkForce/GetNurseList')
    if (response.status) {
      nurseOptions.value = response.data || []
      if (nurseOptions.value.length > 0) {
        selectedNurse.value = nurseOptions.value[0].nurseCode
      }
    }
  } catch (error) {
    console.error('获取护士列表失败:', error)
  }
}

onMounted(() => {
  getNurseList()
})

const weekDays = ['周一','周二','周三','周四','周五','周六','周日']

function getDaysInMonth(year: number, month: number) {
  if (month === 2) {
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0) ? 29 : 28
  }
  if ([4, 6, 9, 11].includes(month)) return 30
  return 31
}

function parseSelectedMonth(val: string) {
  // 例：2025-02 上
  const [yearMonth, half] = val.split(' ')
  const [year, month] = yearMonth.split('-').map(Number)
  return { year, month, half }
}

const days = ref<{date: number, weekday: string}[]>([])
const shifts = ref<string[]>([])

function updateDaysAndShifts() {
  const { year, month, half } = parseSelectedMonth(selectedMonth.value)
  const dayCount = getDaysInMonth(year, month)
  let start = 1, end = dayCount
  if (half === '上') {
    start = 1
    end = Math.min(15, dayCount)
  } else {
    start = 16
    end = dayCount
  }
  const len = end - start + 1
  days.value = Array.from({length: len}, (_, i) => ({
    date: start + i,
    weekday: weekDays[((start + i - 1) % 7)]
  }))
  shifts.value = Array(len).fill('早班')
}

updateDaysAndShifts()

watch(selectedMonth, () => {
  updateDaysAndShifts()
})

const onCancel = () => {
  router.back()
}

const onSubmit = async () => {
  try {
    const { year, month, half } = parseSelectedMonth(selectedMonth.value)
    const schedules = days.value.map((day, index) => ({
      id: 0,
      year: year,
      month: month,
      stage: day.date.toString(),  // 使用日期作为stage值
      nurseCode: selectedNurse.value,
      nurseName: nurseOptions.value.find(n => n.nurseCode === selectedNurse.value)?.name || '',
      workDate: new Date(year, month - 1, day.date).toISOString(),
      workWeek: new Date(year, month - 1, day.date).toISOString(),
      classGroup: shifts.value[index],
      creator: "admin",
      createTime: new Date().toISOString()
    }))

    // 调用添加排班API
    const response = await http.post('api/Workforce/AddWorkforeces', schedules)
    
    if (response.status) {
      ElMessage.success('排班添加成功')
      router.back()
    } else {
      // 如果返回的消息中包含"当前阶段已排班"，显示特定提示
      if (response.message && response.message.includes('当前阶段已排班')) {
        ElMessage.error('该护士在当前阶段已有排班安排')
      } else {
        ElMessage.error(response.message || '添加失败')
      }
    }
  } catch (error) {
    console.error('添加排班失败:', error)
    ElMessage.error('添加排班失败，请检查网络连接')
  }
}
</script>

<style scoped>
.schedule-add-container {
  padding: 20px;
  background-color: #fff;
}

.schedule-header {
  margin-bottom: 30px;
}

.schedule-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  padding: 20px;
}

.schedule-card {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 15px;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-weight: bold;
}

.day-number {
  margin-right: 10px;
}

.weekday {
  color: #606266;
}

.shift-options {
  display: flex;
  flex-direction: column;
}

.shift-radio-group {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.shift-radio {
  margin: 0 !important;
  padding: 8px;
}

.shift-label {
  display: flex;
  align-items: center;
  gap: 5px;
}

.radio-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 5px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  padding: 20px;
}

:deep(.el-radio__label) {
  padding-left: 5px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-select) {
  width: 120px !important;
}

:deep(.el-select.stage-select) {
  width: 180px !important;
}
</style>